<!--
 * @Description: 自定义拖拽进度条组件
 * @Date: 2024-11-29 11:45:57
 * @FilePath: \demod:\12electron\electron-demo\src\renderer\src\components\ProgressBar.vue
-->
<template>
  <div class="progress-bar" ref="progressBar" @mousedown="startDrag" @mouseup="stopDrag" :style="{ height: height + 'px' }">
    <div class="progress" :style="{ width: progressWidth + '%' }"></div>
    <div
      v-if="showCircle"
      class="circle"
      :style="{
        left: progressWidth + '%',
        width: height + 3 + 'px',
        height: height + 3 + 'px',
      }"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';

const props = defineProps({
  // 最大值
  maxValue: {
    type: Number,
    required: true,
  },
  // 当前值
  currentValue: {
    type: Number,
    required: true,
  },
  // 是否显示圆形
  showCircle: {
    type: Boolean,
    default: true,
  },
  // bar高度
  height: {
    type: Number,
    default: 12,
  },
});

const emit = defineEmits(['update:currentValue', 'change']);

const progressBar = ref();
const isDragging = ref(false);

const progressWidth = computed(() => {
  return (props.currentValue / props.maxValue) * 100;
});

const startDrag = (event) => {
  console.log('event: ', event);
  isDragging.value = true;
  updateProgress(event);
};

const stopDrag = (event) => {
  console.log('end: ', event);
  isDragging.value = false;
  emit('change');
};

const updateProgress = (event) => {
  if (isDragging.value) {
    const rect = progressBar.value.getBoundingClientRect();
    const offsetX = event.clientX - rect.left;
    const newProgress = (offsetX / rect.width) * props.maxValue;
    emit('update:currentValue', Math.min(props.maxValue, Math.max(0, newProgress)));
  }
};

onMounted(() => {
  window.addEventListener('mousemove', updateProgress);
});

onUnmounted(() => {
  window.removeEventListener('mousemove', updateProgress);
});
</script>

<style lang="scss" scoped>
.progress-bar {
  position: relative;
  width: 100%;
  background-color: #e0e0e0;
  border-radius: 10px;
  cursor: pointer;
}

.progress {
  position: absolute;
  height: 100%;
  background-color: #0187fe;
  border-radius: 10px;
  transition: width 0.2s ease;
}

.circle {
  position: absolute;
  background-color: #ffffff;
  border-radius: 50%;
  transform: translate(-50%, -2px);
  border: 3px solid #359ffc;
  box-shadow: 0px 0px 5px 2px rgba(31, 30, 30, 0.7);
}
</style>
